'use client';

import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Form, Input, Select, FormInstance, Cascader } from 'antd';
import RichTextEditor from '@/components/RichTextEditor';
import { categoryApi } from '@/apis/category';
import { getUserList } from '@/apis/user';
import { CategoryResponse, InstrumentCreateRequest } from '@/types/instrument';
import { useMessage } from '@/hooks/useMessage';
import FileUpload from '@/components/FileUpload';

const { TextArea } = Input;
const { Option } = Select;



// 用户选项接口
interface UserOption {
  label: string;
  value: number;
}

export interface BasicInfoFormRef {
  getFormData: () => Partial<InstrumentCreateRequest>;
}

interface BasicInfoFormProps {
  form: FormInstance;
  mode: 'create' | 'edit' | 'view';
  initialValues?: Partial<InstrumentCreateRequest>;
  onSubmit?: (values: Partial<InstrumentCreateRequest>) => void;
}

// 工具函数：根据分类id找到路径
function findCategoryPath(categories: CategoryResponse[], id: number): number[] {
  for (const cat of categories) {
    if (cat.id == id) return [cat.id];
    if (cat.children) {
      for (const sub of cat.children) {
        if (sub.id == id) return [cat.id, sub.id];
      }
    }
  }
  return [];
}

const BasicInfoForm = forwardRef<BasicInfoFormRef, BasicInfoFormProps>(({ 
  form, 
  mode, 
  initialValues = {},
  onSubmit
}, ref) => {
  const isReadOnly = mode === 'view';
  const [categories, setCategories] = useState<CategoryResponse[]>([]);
  const [categoriesLoading, setCategoriesLoading] = useState(false);
  const [userOptions, setUserOptions] = useState<UserOption[]>([]);
  const [usersLoading, setUsersLoading] = useState(false);
  const message = useMessage();

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    getFormData: () => {
      const formData = form.getFieldsValue();
      // 如果categoryId是数组（Cascader的值），取最后一个作为实际的categoryId
      if (Array.isArray(formData.categoryId)) {
        formData.categoryId = formData.categoryId[formData.categoryId.length - 1];
      }
      console.log('BasicInfoForm getFormData:', formData);
      return formData;
    }
  }), [form]);

  // 只在挂载时加载分类和用户
  useEffect(() => {
    loadCategories();
    loadUsers();
  }, []);

  // 设置初始值（除了categoryId，因为需要等分类数据加载完成）
  useEffect(() => {
    if (Object.keys(initialValues).length > 0) {
      const { categoryId, ...otherValues } = initialValues;
      form.setFieldsValue(otherValues);
    }
  }, [initialValues, form]);

  // 回显逻辑单独处理
  useEffect(() => {
    if (categories.length > 0 && initialValues.categoryId) {
      const path = findCategoryPath(categories, initialValues.categoryId as number);
      console.log('设置分类回显路径:', path, '原始ID:', initialValues.categoryId);
      form.setFieldValue('categoryId', path);
    }
  }, [categories, initialValues, form]);

  // 图片处理逻辑已移至 FileUpload 组件中

  // 加载仪器分类树
  const loadCategories = async () => {
    setCategoriesLoading(true);
    try {
      // 使用分类树接口获取带层级结构的分类数据
      const categoryTree = await categoryApi.getCategoryTree();
      console.log('仪器分类树数据:', categoryTree);
      setCategories(categoryTree);
    } catch (error) {
      console.error('加载仪器分类失败:', error);
      message.error('加载仪器分类失败，请稍后重试');
    } finally {
      setCategoriesLoading(false);
    }
  };

  // 加载用户列表
  const loadUsers = async () => {
    setUsersLoading(true);
    try {
      const users = await getUserList();
      const options: UserOption[] = users.map(user => ({
        label: `${user.name}(${user.phoneNumber})`,
        value: user.id,
      }));
      setUserOptions(options);
    } catch (error) {
      console.error('加载用户列表失败:', error);
      message.error('加载用户列表失败，请稍后重试');
    } finally {
      setUsersLoading(false);
    }
  };

  // 构造Cascader options
  const cascaderOptions = categories.map(cat => ({
    value: cat.id,
    label: cat.name,
    children: (cat.children || []).map(sub => ({
      value: sub.id,
      label: sub.name,
    })),
  }));


  return (
    <div style={{ maxWidth: '800px' }}>
      <Form
        form={form}
        layout="vertical"
        onFinish={onSubmit}
        initialValues={{
          curatorUserIds: [1], // 默认选择第一个负责人
          operatorUserIds: [],
          ...initialValues
        }}
        disabled={isReadOnly}
      >
        <Form.Item
          label="仪器名称"
          name="name"
          rules={[{ required: !isReadOnly, message: '请输入仪器名称' }]}
        >
          <Input placeholder="请输入" readOnly={isReadOnly} style={{ width: '400px' }} />
        </Form.Item>

        <Form.Item
          label="仪器分类"
          name="categoryId"
          rules={[{ required: !isReadOnly, message: '请选择仪器分类' }]}
        >
          <Cascader
            options={cascaderOptions}
            placeholder={categoriesLoading ? "加载中..." : "请选择仪器分类"}
            disabled={isReadOnly}
            changeOnSelect
            showSearch
            style={{ width: 300 }}
            loading={categoriesLoading}
            notFoundContent={categoriesLoading ? "加载中..." : "暂无分类数据"}
            onChange={(value) => {
              // Cascader需要保存完整路径数组用于显示，同时我们需要最后一个ID用于提交
              console.log('Cascader选择值:', value);
              // 不需要手动设置，让Form自动管理Cascader的值
            }}
          />
        </Form.Item>

        <Form.Item
          label="型号"
          name="model"
        >
          <Input placeholder="请输入" readOnly={isReadOnly} style={{ width: '300px' }} />
        </Form.Item>

        <Form.Item
          label="一句话介绍"
          name="description"
          rules={[{ required: !isReadOnly, message: '请输入一句话介绍' }]}
          extra={!isReadOnly ? "展示在首页及分类页，详情页不展示" : undefined}
        >
          <Input placeholder="请输入" readOnly={isReadOnly} style={{ width: '600px' }} />
        </Form.Item>

        <Form.Item
          label="展示图片"
          name="picImg"
        >
          <FileUpload
            disabled={isReadOnly}
            placeholder="点击上传仪器展示图片"
          />
        </Form.Item>

        <Form.Item
          label="仪器简介"
          name="introduction"
          rules={[{ required: !isReadOnly, message: '请输入仪器简介' }]}
        >
          <TextArea
            rows={6}
            placeholder="请输入文字"
            showCount={!isReadOnly}
            maxLength={1000}
            readOnly={isReadOnly}
          />
        </Form.Item>

        <Form.Item
          label="负责人"
          name="curatorUserIds"
          rules={[{ required: !isReadOnly, message: '请选择负责人' }]}
          extra={!isReadOnly ? "选择操作权限为负责人的人员，可选多个" : undefined}
        >
          <Select
            mode="multiple"
            placeholder="请选择"
            allowClear
            disabled={isReadOnly}
          >
            {userOptions.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="操作员"
          name="operatorUserIds"
          extra={!isReadOnly ? "选择操作权限为操作员的人员，可选多个" : undefined}
        >
          <Select
            mode="multiple"
            placeholder="请选择"
            allowClear
            disabled={isReadOnly}
          >
            {userOptions.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="专业咨询二维码"
          name="qrCodeImg"
        >
          <FileUpload
            disabled={isReadOnly}
            placeholder="上传企业微信二维码图片"
          />
        </Form.Item>

        <Form.Item
          label="负责人图片"
          name="curatorImg"
        >
          <FileUpload
            disabled={isReadOnly}
            placeholder="上传负责人图片"
          />
        </Form.Item>

        <Form.Item
          label="负责人介绍"
          name="curatorIntroduction"
          rules={[{ required: !isReadOnly, message: '请输入负责人介绍' }]}
        >
          <RichTextEditor
            placeholder="请输入负责人介绍"
            height={200}
          />
        </Form.Item>

        <Form.Item
          label="详细介绍"
          name="detailIntroduction"
          rules={[{ required: !isReadOnly, message: '请输入详细介绍' }]}
        >
          <RichTextEditor
            placeholder="请输入详细介绍"
            height={200}
          />
        </Form.Item>
      </Form>
    </div>
  );
});

BasicInfoForm.displayName = 'BasicInfoForm';

export default BasicInfoForm; 